import React, {Component, createRef, RefObject} from 'react'
import {Button, Card, Form, Input, message, Popconfirm, Spin} from 'antd'
import {RouteComponentProps, withRouter} from 'react-router-dom'
import {Store, ValidateErrorEntity} from 'rc-field-form/lib/interface'
import {FormInstance} from 'antd/lib/form'
import ArticleInfo from "../../types/ArticleInfo";
import {modifyArticle, queryArticleInfo} from "../../requests/article";
import wangeditor from 'wangeditor'
import {getRes} from "../../configFile";


interface IProps extends RouteComponentProps<{ id: string }> { }
interface IState {
    articleID: number
    isLoading: boolean
    articleInfo: ArticleInfo | undefined
    editorContent: string
}
class SpecificModifyArticle extends Component<IProps, IState> {

    constructor(props: IProps) {
        super(props)
        this.state = {
            editorContent: '',
            isLoading: true,
            articleID: Number.parseInt(this.props.match.params.id),
            articleInfo: undefined
        }
    }

    editorRef: RefObject<HTMLDivElement> = createRef()
    //创建Form引用
    formRef = React.createRef<FormInstance>()

    //编辑器实例声明 再didmount后操作DOM
    editor: any

    //模态框样式
    modalLayout = {
        labelCol: { span: 2 },
        wrapperCol: { span: 22 },
    }
    tailLayout = {
        wrapperCol: { offset: 2 },
    };

    //初始化富文本编辑器
    initEditor = () => {
        this.editor = new wangeditor(this.editorRef.current)
        this.editor.customConfig.zIndex = 100
        this.editor.customConfig.onchange = (htmlContent: string) => {
            if (this.formRef.current)
                this.formRef.current.setFieldsValue({ 'content': htmlContent })
        }
        this.editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
        this.editor.create()
    }

    componentDidMount = async () => {
        this.initEditor()       //操作DOM初始化editor
        try {
            const res = getRes(await queryArticleInfo(this.state.articleID))
            if (res.isSuccessful === true) {
                this.setState({
                    ...this.state,
                    articleInfo: res.data
                })
                this.editor.txt.html(res.data.content)
                //设置表单域    实例不为空
                if (this.formRef.current)
                    this.formRef.current.setFieldsValue(res.data)
            } else {
                message.error(res.message)
            }
            this.setState({
                ...this.state,
                isLoading: false
            })
        } catch (err) {
            message.error(err.toString())
        }
    }

    //放弃修改
    modifyAbort = () => {
        this.props.history.goBack()
    }

    //提交失败
    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };


    //提交成功
    onFinish: (values: Store) => void = async values => {
        //articleInfo不为空
        if (!!this.state.articleInfo) {
            const paraTmp = {
                articleID: this.state.articleID,
                title: values.title,
                content: values.content,
            }

            this.setState({
                ...this.state,
                isLoading: true
            })

            try {
                const res = getRes(await modifyArticle(paraTmp))
                if (res.isSuccessful === true) {
                    message.success("修改成功")
                    this.props.history.goBack()
                } else {
                    message.error("修改失败")
                }
            } catch (err) {
                message.error(JSON.stringify(err))
            } finally {
                this.setState({
                    ...this.state,
                    isLoading: false
                })
            }
        }
    }

    render() {
        return (
            <Spin spinning={this.state.isLoading}>
                <Card
                    extra={<Popconfirm
                        placement="topRight"
                        title='确定放弃更改吗？'
                        onConfirm={this.modifyAbort}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button danger>放弃更改</Button>
                    </Popconfirm>}
                    title={this.state.articleInfo?.title}
                >
                    <Form
                        onFinishFailed={this.onFinishFailed}
                        onFinish={this.onFinish}
                        ref={this.formRef}
                        {...this.modalLayout}
                        name="articleModify"
                        hideRequiredMark
                    >

                        <Form.Item
                            name="title"
                            label="文章标题"
                            rules={[
                                {
                                    required: true,
                                    message: '文章标题必填',
                                },
                            ]}
                            hasFeedback
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="content"
                            label="文章内容"
                            rules={[
                                {
                                    required: true,
                                    message: '文章内容必填',
                                },
                            ]}
                        >
                            <div className="editorDiv" ref={this.editorRef} />
                        </Form.Item>
                        <Form.Item {...this.tailLayout}>
                            <Button type="primary" htmlType="submit" size="large">
                                确认修改
                            </Button>
                        </Form.Item>

                    </Form>
                </Card>
            </Spin>
        )
    }
}

export default withRouter(SpecificModifyArticle)